#ifndef __CONN_READER_H__
#define __CONN_READER_H__


#include <memory>
#include <vector>
#include <functional>
#include <string>

#include "common.h"
#include "packet_base.h"


class ConnReader
{
public:
    enum EStatus{
        kEAGAIN = 1,
        kCLOSE = 2,
        kERROR = 3,
        kHEADER_FINISHED = 4,
        kBODY_FINISHED = 5,
    };

private:
    int fd_;

private:
    EStatus ReadHeader();
    EStatus ReadBody();

public:
    ConnReader();
    ~ConnReader();

    inline void SetFd(int fd){
        fd_ = fd;
    }
    inline int GetFd(){
        return fd_;
    }

    inline void RegisterCb(std::function<void(int, PacketBase&)> cb){
        cb_ = cb;
    }

    void Reset();

    /**
     * @brief 从fd_中读取数据
     * 
     * @return int -1为error或close，0是EAGAIN，1为正常
     */
    int Recv();

    void HandleData();

public:
    uint32_t body_len_;  // 当前包体长度，0表示还未解析头部
    uint32_t cmd_;
    uint32_t origin_body_len_;  // 大端字节序
    uint32_t origin_cmd_;  // 大端字节序
    char buff_[common::PROTO_BUFFER_LEN];

    uint32_t index_;  // 已解析的长度

    std::function<void(int, PacketBase&)> cb_;
};


#endif  // __CONN_READER_H__